from openai import OpenAI
from langfuse import Langfuse
import os

# 初始化Langfuse客户端
langfuse = Langfuse(
    public_key=os.getenv("LANGFUSE_PUBLIC_KEY"),
    secret_key=os.getenv("LANGFUSE_SECRET_KEY"),
    host="https://cloud.langfuse.com" # 或你的自托管地址
)

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def customer_service_chat(user_message):
    # 创建一个跟踪轨迹
    trace = langfuse.trace(name="customer_service_chat")
    
    # 创建生成步骤
    generation = trace.generation(
        name="customer_service_llm_call",
        model="gpt-3.5-turbo",
    )
    
    prompt = ... # 同上

    response = client.chat.completions.create(...) # 同上
    
    # 将输出和成本等信息记录到生成步骤中
    generation.end(
        output=response.choices[0].message.content,
        usage=response.usage # 记录token用量
        # model_parameters={...} 还可以记录温度等参数
    )
    
    return response.choices[0].message.content

# 调用
answer = customer_service_chat("我订单号12345的物流到哪里了？")
print(answer)